package com.example.pre.tools;

import java.util.Collection;

import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/*
 * json转换
 */
@SuppressWarnings("deprecation")
public class JsonConvert {
	public static ObjectMapper objectMapper = new ObjectMapper();

	static {
		objectMapper.setVisibilityChecker(objectMapper.getSerializationConfig().getDefaultVisibilityChecker()
				.withFieldVisibility(Visibility.ANY).withGetterVisibility(Visibility.NONE)
				.withSetterVisibility(Visibility.NONE).withCreatorVisibility(Visibility.NONE));
	}

	/**
	 * json字符串转换为指定对象
	 * 
	 * @param jsonObject
	 * @param beanClass
	 * @return
	 */
	public static <T> T toBean(Object jsonObject, Class<T> beanClass) {
		try {
			return objectMapper.readValue(jsonObject.toString(), beanClass);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * json字符串转换成对象集合
	 * 
	 * @param jsonObjects
	 * @param beanClass
	 * @return
	 */
	public static <T> Collection<T> toBeans(Object jsonObjects, Class<T> beanClass) {

		JavaType javaType = objectMapper.getTypeFactory().constructParametricType(Collection.class, beanClass);
		try {
			@SuppressWarnings("unchecked")
			Collection<T> dirs = (Collection<T>) objectMapper.readValue(jsonObjects.toString(), javaType);
			return dirs;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 对象转换成json字符串
	 * 
	 * @param obj
	 * @return
	 */
	public static String getJsonArrStrFromList(Object obj) {

		String jsonStr = null;

		if (obj == null) {
			return "{}";
		}
		try {
			jsonStr = objectMapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			throw new RuntimeException(e);
		}

		return jsonStr;
	}

}
